<?php
namespace App\Model;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WishDefender extends BaseModel
{
    protected $connection = 'api';
    protected $table = 'wish_defender_config';
    protected $wPoolTable = 'wish_defender_pool';
    protected $wPoolConfigTable = 'wish_defender_pool_config';
    protected $wOrderTable = 'wish_defender_order';
    protected $wDrawTable = 'wish_defender_draw';
    protected $wWhiteTable = 'wish_defender_white';
    protected $wStatisticsTable = 'wish_defender_statistics';
    protected $userTable = 'user';
    protected $room_table = 'room';//房间表
    protected $union_room = 'union_room';//公会房间
    protected $union = 'union';//公会表
    protected $unionUserTable = 'union_user';//公会用户
    protected $giftTable = 'gift_library';//礼物表
    protected $DefenderDrawTable = 'defender_draw';//抽奖活动表
    protected $wGiftTable = 'wish_defender_gift';//擂主玩法展示礼物
    protected $wSendGiftTable = 'wish_defender_send_gift';//擂主玩法展示礼物
    protected $wPoolUserTable = 'wish_defender_pool_user';//擂主玩法个人池用户
    protected $defenderwinnerTable = 'wish_defender_winner';//擂主奖励发放记录

    //擂主玩法设置单次抽奖消耗数量
    public function wishDefenderSetNeedNum($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderSetNeedNum', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法设置全服擂主值和扣减擂主值
    public function wishDefenderSetStartNum($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderSetStartNum', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法设置档位抽取次数
    public function wishDefenderSetDrawNum($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderSetDrawNum', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法设置奖池开启/关闭
    public function wishDefenderSetPoolStatus($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderSetPoolStatus', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法保存奖池配置
    public function wishDefenderSavePoolConfig($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderSavePoolConfig', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法新增奖池
    public function wishDefenderAddPool($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderAddPool', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法编辑奖池
    public function wishDefenderEditPool($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderEditPool', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法更新奖池缓存
    public function wishDefenderPoolReset($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderPoolReset', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法奖池列表
    public function wishDefenderPoolList(Request $request)
    {
        $status = $request->input('status');
        $poolLevel = $request->input('pool_level');

        $query = DB::connection($this->connection)->table($this->wPoolTable)->where('pool_type', 1)->where('pool_level',$poolLevel);
        if(!empty($status)) {
            $query = $query->where('status', $status);
        }

        $list = $query->get();
        $list = objToArray($list);

        return ['code'=>20000, 'data'=>$list, 'msg'=>'ok'];
    }

    //擂主玩法配置信息
    public function wishDefenderConfig(Request $request)
    {
        $list = DB::connection($this->connection)->table($this->table)->first();
        $list = objToArray($list);
        $list['draw_img_1a'] = build_image($list['draw_img_1a']);
        $list['draw_img_1b'] = build_image($list['draw_img_1b']);
        $list['draw_img_2a'] = build_image($list['draw_img_2a']);
        $list['draw_img_2b'] = build_image($list['draw_img_2b']);
        //许愿卡价值
        $lickId = 1000;
        $DefenderInfo = DB::connection($this->connection)->table($this->DefenderDrawTable)->where('id', $lickId)->first();
        $DefenderInfo = objToArray($DefenderInfo);
        $list['price'] = empty($DefenderInfo['price']) ? 0 : $DefenderInfo['price'];

        return ['code'=>20000, 'data'=>$list, 'msg'=>'ok'];
    }

    //擂主玩法奖池配置列表
    public function wishDefenderPoolConfigList(Request $request)
    {
        $poolId = $request->input('pool_id');
        if(empty($poolId)) {
            return ['code'=>50001, 'data'=>[], 'msg'=>'参数错误'];
        }

        $query = DB::connection($this->connection)
            ->table($this->wPoolConfigTable.' as a')
            ->leftJoin($this->giftTable.' as b' ,'a.gift_id','=','b.gift_id')
            ->where('a.pool_id', $poolId)
            ->select(['a.id','a.pool_id','a.item_no','a.gift_id','a.gift_num','b.name as gift_name','b.image as gift_image','b.price as gift_price']);

        $list = $query->orderBy('a.item_no', 'asc')->get();
        $list = objToArray($list);

        return ['code'=>20000, 'data'=>$list, 'msg'=>'ok'];
    }

    //擂主玩法奖池配置剩余数量
    public function wishDefenderPoolConfigNum($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderPoolConfigNum', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法新增白名单
    public function wishDefenderAddWhite($data, $user){
        $data['admin_id'] = $user['id'];
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderAddWhite', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法删除白名单
    public function wishDefenderDelWhite($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderDelWhite', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法白名单列表
    public function wishDefenderWhiteList(Request $request)
    {
        $user_id = $request->input('user_id');
        $gift_id = $request->input('gift_id');
        $uuid = $request->input('uuid');
        $status = $request->input('status');
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $pool_level = $request->input('pool_level');

        $query = DB::connection($this->connection)
            ->table($this->wWhiteTable.' as a')
            ->leftJoin($this->giftTable.' as b' ,'a.gift_id','=','b.gift_id')
            ->leftJoin($this->userTable.' as c' ,'a.user_id','=','c.user_id')
            ->select(['a.id','a.user_id','a.gift_id','a.status','a.order_id','a.admin_id','a.created_at'
                ,'b.name as gift_name','b.image as gift_image','b.price as gift_price'
                ,'c.uuid','c.nickname'])
//            ->where('a.pool_id', 0)
            ->where('a.pool_level',$pool_level)
            ->where('a.is_delete', 0);
        if(!empty($user_id)) {
            $query = $query->where('a.user_id', $user_id);
        }
        if(!empty($gift_id)) {
            $query = $query->where('b.gift_id', $gift_id);
        }
        if(!empty($uuid)) {
            $query = $query->where('c.uuid', $uuid);
        }
        if($status >= 0) {
            $query = $query->where('a.status', $status);
        }
        if(!empty($date_st)) {
            $query = $query->where('a.created_at', '>=', date("Y-m-d H:i:s", strtotime($date_st)));
        }
        if(!empty($date_ed)) {
            $query = $query->where('a.created_at', '<=', date("Y-m-d H:i:s", strtotime($date_ed)));
        }

        $list = $query->orderBy('a.status', 'asc')->orderBy('a.id', 'desc')->get();
        $list = objToArray($list);
        if(!empty($list)) {
            $adminIds = array_column($list, 'admin_id');
            $adminList = DB::table('users')->whereIn('id', $adminIds)->select(['id','name'])->get();
            $adminList = array_column(objToArray($adminList), null, 'id');

            foreach($list as $key=>$val) {
                $val['admin_name'] = empty($adminList[$val['admin_id']]['name']) ? '' : $adminList[$val['admin_id']]['name'];
                $list[$key] = $val;
            }
        }

        return ['code'=>20000, 'data'=>$list, 'msg'=>'ok'];
    }

    //擂主玩法抽奖明细列表
    public function wishDefenderDrawList(Request $request)
    {
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $user_id = $request->input('user_id');
        $pool_level = $request->get('pool_level',1000);
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $query = DB::connection($this->connection)->table($this->wOrderTable);
        $query = $query->where('pool_level', $pool_level);
        if(!empty($date_st)) {
            $query = $query->where('created_at', '>=', date("Y-m-d H:i:s", strtotime($date_st)));
        }
        if(!empty($date_ed)) {
            $query = $query->where('created_at', '<=', date("Y-m-d H:i:s", strtotime($date_ed)));
        }
        if(!empty($user_id)) {
            $query = $query->where('user_id', $user_id);
        }
        $data = $query->orderBy('id', 'desc')->paginate($limit, ['*'], 'page', $page);
        $data = objToArray($data);

        $result = ['list'=>[], 'total'=>0];
        if(!empty($data['data'])) {
            $result['total'] = $data['total'];
            $userIds = array_column($data['data'], 'user_id');
            $userList = DB::connection($this->connection)->table($this->userTable)->whereIn('user_id', $userIds)->select('user_id','nickname','uuid')->get();
            $userList = array_column(objToArray($userList), null, 'user_id');

            $orderIds = array_column($data['data'], 'id');
            $drawList = DB::connection($this->connection)->table($this->wDrawTable)
                ->whereIn('order_id', $orderIds)
                ->selectRaw('sum(gift_num) as gift_num, sum(prop_num) as prop_num, sum(prop_diamond_num) as prop_diamond_num, sum(reward_diamond_num) as reward_diamond_num, order_id, gift_id, user_id')
                ->groupBy('order_id', 'gift_id')
                ->get();
            $drawList = self::objToArray($drawList);
            $list = array_column($data['data'], null, 'id');

            $giftIds = array_column($drawList, 'gift_id');
            $giftList = DB::connection($this->connection)->table($this->giftTable)->whereIn('gift_id', $giftIds)->select(['gift_id','name','image','price'])->get();
            $giftList = array_column(objToArray($giftList), null, 'gift_id');

            foreach($drawList as $key=>$val) {
                $val['created_at'] = $list[$val['order_id']]['created_at'];
                $val['giftName'] = empty($giftList[$val['gift_id']]['name']) ? '' : $giftList[$val['gift_id']]['name'];
                $val['nickname'] = empty($userList[$val['user_id']]['nickname']) ? '' : $userList[$val['user_id']]['nickname'];
                $val['uuid'] = empty($userList[$val['user_id']]['uuid']) ? '' : $userList[$val['user_id']]['uuid'];

                $drawList[$key] = $val;
            }
            array_multisort(array_column($drawList, 'order_id'), SORT_DESC, $drawList);

            $result['list'] = $drawList;
        }

        return ['code'=>20000, 'data'=>$result, 'msg'=>'ok'];
    }
    //擂主玩法抽奖明细列表
    public function wishDefenderSendDrawList(Request $request)
    {
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $user_id = $request->input('user_id');
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $query = DB::connection($this->connection)->table($this->defenderwinnerTable);
        if(!empty($date_st)) {

            $query = $query->where('created_at', '>=', date("Y-m-d H:i:s", strtotime($date_st)));
        }
        if(!empty($date_ed)) {
            $query = $query->where('created_at', '<=', date("Y-m-d H:i:s", strtotime($date_ed)));
        }
        if(!empty($user_id)) {
            $query = $query->where('user_id', $user_id);
        }
        $data = $query->orderBy('id', 'desc')->paginate($limit, ['*'], 'page', $page);
        $data = objToArray($data);
        $result = ['list'=>[], 'total'=>0];
        if(!empty($data['data'])) {
            $result['total'] = $data['total'];
            $userIds = array_column($data['data'], 'user_id');
            $userList = DB::connection($this->connection)->table($this->userTable)->whereIn('user_id', $userIds)->select('user_id','nickname','uuid')->get();
            $userList = array_column(objToArray($userList), null, 'user_id');
            $giftIds = array_column($data['data'], 'gift_id');
            $giftList = DB::connection($this->connection)->table($this->giftTable)->whereIn('gift_id', $giftIds)->select(['gift_id','name','image','price'])->get();
            $giftList = array_column(objToArray($giftList), null, 'gift_id');
            $orderIds = array_column($data['data'], 'id');
            $drawList = DB::connection($this->connection)->table($this->defenderwinnerTable)
                ->whereIn('id', $orderIds)
                ->get();
            $drawList = self::objToArray($drawList);
            foreach($drawList as $key=>$val) {
                $val['giftName'] = empty($giftList[$val['gift_id']]['name']) ? '' : $giftList[$val['gift_id']]['name'];
                $val['nickname'] = empty($userList[$val['user_id']]['nickname']) ? '' : $userList[$val['user_id']]['nickname'];
                $val['uuid'] = empty($userList[$val['user_id']]['uuid']) ? '' : $userList[$val['user_id']]['uuid'];
                $val['gift_num'] =1;
                switch ($val['pool_level']) {
                    case 1000:
                        $val['pool_level'] ="一阶段";
                        break;
                    case 1001:
                        $val['pool_level'] ="二阶段";
                        break;
                    case 1002:
                        $val['pool_level'] ="三阶段";
                        break;
                    case 1003:
                        $val['pool_level'] ="四阶段";
                        break;
                    default:
                        break;
                }
                $drawList[$key] = $val;
            }
            array_multisort(array_column($drawList, 'id'), SORT_DESC, $drawList);
            $result['list'] = $drawList;

        }

        return ['code'=>20000, 'data'=>$result, 'msg'=>'ok'];
    }

    //擂主玩法抽奖用户汇总数据
    public function wishDefenderUserStatistic(Request $request)
    {
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $user_id = $request->input('user_id');
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $pool_level = $request->input('pool_level', 0);
        if(empty($pool_level)){
            return ['code'=>4000, 'data'=>[], 'msg'=>'缺少奖池级别'];
        }

        $query = DB::connection($this->connection)->table($this->wOrderTable)
            ->where('pool_level', $pool_level)
            ->selectRaw('id,user_id, sum(prop_diamond_num) as prop_diamond_num, sum(reward_diamond_num) as reward_diamond_num, max(created_at) AS last_at, sum(num) as draw_num');
        if(!empty($date_st)) {
            $query = $query->where('created_at', '>=', date("Y-m-d H:i:s", strtotime($date_st)));
        }
        if(!empty($date_ed)) {
            $query = $query->where('created_at', '<=', date("Y-m-d H:i:s", strtotime($date_ed)));
        }
        if(!empty($user_id)) {
            $query = $query->where('user_id', $user_id);
        }
        $data = $query->groupBy('user_id')->orderBy('last_at', 'desc')->paginate($limit, ['*'], 'page', $page);
        $data = objToArray($data);

        //汇总数据
        $query2 = DB::connection($this->connection)->table($this->wOrderTable)
            ->where('pool_level', $pool_level)
            ->selectRaw('count(DISTINCT user_id) as user_num, sum(prop_diamond_num) as prop_diamond_num, sum(reward_diamond_num) as reward_diamond_num, sum(num) as draw_num');
        $query2 = $query2->whereNotIn('user_id', [10039,10019]);
        if(!empty($date_st)) {
            $query2 = $query2->where('created_at', '>=', date("Y-m-d H:i:s", strtotime($date_st)));
        }
        if(!empty($date_ed)) {
            $query2 = $query2->where('created_at', '<=', date("Y-m-d H:i:s", strtotime($date_ed)));
        }
        $data2 = $query2->first();
        $data2 = objToArray($data2);
        $data2['user_num'] = empty($data2['user_num']) ? 0 : $data2['user_num'];
        $data2['prop_diamond_num'] = empty($data2['prop_diamond_num']) ? 0 : $data2['prop_diamond_num'];
        $data2['reward_diamond_num'] = empty($data2['reward_diamond_num']) ? 0 : $data2['reward_diamond_num'];
        $data2['output_ratio'] = ($data2['reward_diamond_num']>0) ? round(($data2['reward_diamond_num']/$data2['prop_diamond_num'])*100,4) : '0.0000';
        $data2['draw_num'] = empty($data2['draw_num']) ? 0 : $data2['draw_num'];

        $result = ['list'=>[], 'all'=>$data2, 'total'=>0];
        if(!empty($data['data'])) {
            $result['total'] = $data['total'];

            $userIds = array_column($data['data'], 'user_id');
            $userList = DB::connection($this->connection)->table($this->userTable)->whereIn('user_id', $userIds)->select('user_id','nickname','uuid')->get();
            $userList = array_column(objToArray($userList), null, 'user_id');

            $list = [];
            foreach($data['data'] as $key=>$val) {
                $val['nickname'] = empty($userList[$val['user_id']]['nickname']) ? '' : $userList[$val['user_id']]['nickname'];
                $val['uuid'] = empty($userList[$val['user_id']]['uuid']) ? '' : $userList[$val['user_id']]['uuid'];
                $val['output_ratio'] = ($val['reward_diamond_num']>0) ? round(($val['reward_diamond_num']/$val['prop_diamond_num'])*100,4) : '0.0000';
                $val['profit_loss'] = $val['reward_diamond_num'] - $val['prop_diamond_num'];
                //获取用户设备信息
                $request->offsetSet('user_id',$val['user_id']);
                $res = $this->WishDefenderUserStatisticChild($request);
                $val['has_child'] = empty($res) ? 0 : 1;
                $list[$key] = $val;
            }

            $result['list'] = $list;
        }

        return ['code'=>20000, 'data'=>$result, 'msg'=>'ok'];
    }

    //擂主玩法抽奖用户汇总数据(同设备查询)
    public function WishDefenderUserStatisticChild(Request $request){
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $user_id = $request->input('user_id');
        $pool_level = $request->input('pool_level', 0);
        do{
            $code = 20000;
            $msg = 'ok';
            $data = [];
            if(empty($user_id)){
                $code = 40000;
                break;
            }
            //获取用户设备信息
            $userInfo = DB::connection($this->connection)->table($this->userTable)->where('user_id',$user_id)->first();
            $userInfo = objToArray($userInfo);
            $deviceStr = $userInfo['guid'];
            //获取同一设备的用户id
            $userArr = DB::connection($this->connection)->table($this->userTable)->where('guid',$deviceStr)->where('user_id','!=',$user_id)->get();
            $userArr = objToArray($userArr);
            $userIds = array_column($userArr,'user_id');
            $userInfos = array_column($userArr,null,'user_id');

            $query = DB::connection($this->connection)->table($this->wOrderTable)
                ->selectRaw('user_id, sum(prop_diamond_num) as prop_diamond_num, sum(reward_diamond_num) as reward_diamond_num, max(created_at) AS last_at, sum(num) as draw_num');
            $query = $query->where('pool_level', $pool_level);
            $query = $query->whereIn('user_id', $userIds);
            if(!empty($date_st)) {
                $query = $query->where('created_at', '>=', date("Y-m-d H:i:s", strtotime($date_st)));
            }
            if(!empty($date_ed)) {
                $query = $query->where('created_at', '<=', date("Y-m-d H:i:s", strtotime($date_ed)));
            }

            $res = $query->groupBy('user_id')->orderBy('last_at', 'desc')->get();
            $res = objToArray($res);
            foreach($res as $key=>$val) {
                $val['nickname'] = empty($userInfos[$val['user_id']]['nickname']) ? '' : $userInfos[$val['user_id']]['nickname'];
                $val['uuid'] = empty($userInfos[$val['user_id']]['uuid']) ? '' : $userInfos[$val['user_id']]['uuid'];
                $val['output_ratio'] = ($val['reward_diamond_num']>0) ? round(($val['reward_diamond_num']/$val['prop_diamond_num'])*100,4) : '0.0000';
                $val['profit_loss'] = $val['reward_diamond_num'] - $val['prop_diamond_num'];

                $data[$key] = $val;
            }

        }while(false);
        return compact('code','data','msg');
    }

    //擂主玩法抽奖每日统计
    public function wishDefenderDayStatistic(Request $request)
    {
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $limit = $request->input('limit', 10);
        $pool_level = $request->get('pool_level', 1000);
        $page = $request->input('page', 1);
        if(empty($date_st)) $date_st = '2024-01-01';
        if(empty($date_ed)) $date_ed = '2124-01-01';
        $date_st = date("Ymd", strtotime($date_st));
        $date_ed =  date("Ymd", strtotime($date_ed));

        $now = time();
        $ymd = date("Ymd", $now);
        //当日统计
        $today = [];
        if($page <= 1) {
            if($date_st<=$ymd && $ymd<=$date_ed) {
                $today = DB::connection($this->connection)->table($this->wOrderTable)
                    ->where('created_at', '>=', date("Y-m-d 00:00:00", $now))
                    ->where('created_at', '<=', date("Y-m-d 23:59:59", $now))
                    ->where('pool_level', $pool_level)
                    ->selectRaw('count(DISTINCT user_id) as user_num, sum(num) as draw_num, sum(prop_num) as prop_num, sum(prop_diamond_num) as prop_diamond_num, sum(reward_diamond_num) as reward_diamond_num')
                    ->first();
                $today = self::objToArray($today);
            }
        }

        $query = DB::connection($this->connection)->table($this->wStatisticsTable);
        $query = $query->where('pool_level', $pool_level);
        if(!empty($date_st)) {
            $query = $query->where('ymd', '>=', $date_st);
        }
        if(!empty($date_ed)) {
            $query = $query->where('ymd', '<=', $date_ed);
        }
        $data = $query->orderBy('ymd', 'desc')->paginate($limit, ['*'], 'page', $page);
        $data = objToArray($data);

        $result = ['list'=>[], 'total'=>0];
        if(!empty($data['data'])) {
            $result['total'] = $data['total'];
            $result['list'] = $data['data'];
        }

        if(!empty($today)) {
            $today['id'] = 0;
            $today['ymd'] = $ymd;
            $today['user_num'] = empty($today['user_num']) ? 0 : $today['user_num'];
            $today['draw_num'] = empty($today['draw_num']) ? 0 : $today['draw_num'];
            $today['prop_num'] = empty($today['prop_num']) ? 0 : $today['prop_num'];
            $today['prop_diamond_num'] = empty($today['prop_diamond_num']) ? 0 : $today['prop_diamond_num'];
            $today['reward_diamond_num'] = empty($today['reward_diamond_num']) ? 0 : $today['reward_diamond_num'];
            $today['profit_loss'] = $today['prop_diamond_num'] - $today['reward_diamond_num'];
            array_unshift($result['list'], $today);
        }

        return ['code'=>20000, 'data'=>$result, 'msg'=>'ok'];
    }

    //擂主玩法新增展示礼物
    public function wishDefenderAddGift($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderAddGift', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法删除展示礼物
    public function wishDefenderDelGift($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderDelGift', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法奖品列表
    public function wishDefenderGiftList(Request $request)
    {
        $pool_level = $request->get('pool_level',1000);
        $list = DB::connection($this->connection)->table($this->wGiftTable)->where('pool_level',$pool_level)->where('is_delete', 0)->orderBy('sort', 'asc')->get();
        $list = objToArray($list);
        if(!empty($list)) {
            $giftIds = array_column($list, 'gift_id');
            $giftList = DB::connection($this->connection)->table($this->giftTable)->whereIn('gift_id', $giftIds)->get();
            $giftList = array_column(objToArray($giftList), null, 'gift_id');

            foreach($list as &$val) {
                $val['gift_name'] = empty($giftList[$val['gift_id']]['name']) ? '' : $giftList[$val['gift_id']]['name'];
                $val['gift_price'] = empty($giftList[$val['gift_id']]['price']) ? '' : $giftList[$val['gift_id']]['price'];
            }
        }

        return $list;
    }



    //擂主玩法新增赠送展示礼物
    public function wishDefenderSendAddGift($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderSendAddGift', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法删除赠送展示礼物
    public function wishDefenderSendDelGift($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderSendDelGift', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法赠送奖品列表
    public function wishDefenderSendGiftList(Request $request)
    {
        $pool_level = $request->get('pool_level',1000);
        $list = DB::connection($this->connection)->table($this->wSendGiftTable)->where('pool_level',$pool_level)->where('is_delete', 0)->orderBy('sort', 'asc')->get();
        $list = objToArray($list);
        if(!empty($list)) {
            $giftIds = array_column($list, 'gift_id');
            $giftList = DB::connection($this->connection)->table($this->giftTable)->whereIn('gift_id', $giftIds)->get();
            $giftList = array_column(objToArray($giftList), null, 'gift_id');

            foreach($list as &$val) {
                $val['gift_name'] = empty($giftList[$val['gift_id']]['name']) ? '' : $giftList[$val['gift_id']]['name'];
                $val['gift_price'] = empty($giftList[$val['gift_id']]['price']) ? '' : $giftList[$val['gift_id']]['price'];
            }
        }

        return $list;
    }

    //擂主玩法新增个人池用户
    public function wishDefenderAddPoolUser($data, $user){
        $data['admin_id'] = $user['id'];
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderAddPoolUser', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法删除个人池用户
    public function wishDefenderDelPoolUser($data, $user){
        $data['admin_id'] = $user['id'];
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderDelPoolUser', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法查看个人奖池剩余数
    public function wishDefenderPoolSelfConfigNum($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderPoolSelfConfigNum', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法个人池用户列表
    public function wishDefenderPoolUserList(Request $request)
    {
        $user_id = $request->input('user_id');
        $in_pool = $request->input('in_pool', 0);
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);

        $query = DB::connection($this->connection)
            ->table($this->wPoolUserTable.' as a')
            ->leftJoin($this->userTable.' as b' ,'a.user_id','=','b.user_id')
            ->leftJoin($this->wPoolTable.' as c' ,'a.pool_id','=','c.id')
            ->select(['a.id','a.user_id','a.admin_id','a.add_time','a.deladmin_id','a.del_time','a.is_delete','a.pool_id','a.out_diamond_num'
                ,'b.uuid as user_uuid','b.nickname as user_nickname'
                ,'c.pool_name','c.pool_type'
            ]);
        if(!empty($user_id)) {
            $query = $query->where('a.user_id', $user_id);
        }
        if($in_pool == 1) {
            $query = $query->where('a.is_delete', 0);
        }elseif($in_pool == 2) {
            $query = $query->where('a.is_delete', 1);
        }
        $data = $query->orderBy('a.id', 'desc')->paginate($limit, ['*'], 'page', $page);
        $data = objToArray($data);

        $result = ['list'=>[], 'total'=>0];
        if(!empty($data['data'])) {
            $result['total'] = $data['total'];
            $result['list'] = $data['data'];
        }

        if(!empty($result['list'])) {
            $adminIds = array_merge(array_column($result['list'], 'admin_id'),array_column($result['list'], 'deladmin_id'));
            $adminList = DB::table('users')->whereIn('id', $adminIds)->select(['id','name'])->get();
            $adminList = array_column(objToArray($adminList), null, 'id');

            $userIds = array_column($result['list'], 'user_id');
            $unionUserList = DB::connection($this->connection)
                ->table($this->unionUserTable.' as a')
                ->leftJoin($this->union.' as b' ,'a.un_id','=','b.id')
                ->select(['a.id','a.un_id','a.user_id','b.un_user_id','b.name'])
                ->whereIn('a.user_id', $userIds)
                ->where('b.authentication_status', '>', 0)
                ->where('b.stop', 1)
                ->get();
            $unionUserList = array_column(objToArray($unionUserList), null, 'user_id');

            foreach($result['list'] as $key=>$val) {
                if(empty($val['admin_id'])) {
                    $val['admin_name'] = '系统';
                }else{
                    $val['admin_name'] = empty($adminList[$val['admin_id']]['name']) ? '' : $adminList[$val['admin_id']]['name'];
                }
                if(empty($val['deladmin_id']) && $val['is_delete']==1) {
                    $val['deladmin_name'] = '系统';
                }else{
                    $val['deladmin_name'] = empty($adminList[$val['deladmin_id']]['name']) ? '' : $adminList[$val['deladmin_id']]['name'];
                }
                $val['union_id'] = empty($unionUserList[$val['user_id']]['un_id']) ? '' : $unionUserList[$val['user_id']]['un_id'];
                $val['union_name'] = empty($unionUserList[$val['user_id']]['name']) ? '' : $unionUserList[$val['user_id']]['name'];

                $result['list'][$key] = $val;
            }
        }

        return $result;
    }

    //擂主玩法奖池已配置礼物列表
    public function wishDefenderPoolGift(Request $request)
    {
        $list = [];
        $pool_level = $request->get('pool_level',1000);
        do {
            $info = DB::connection($this->connection)->table($this->wPoolTable)
                ->where('pool_level',$pool_level)
                ->where('status', 1)
                ->first();
            $info = objToArray($info);
            if(empty($info)) {
                break;
            }

            $query = DB::connection($this->connection)
                ->table($this->wPoolConfigTable.' as a')
                ->leftJoin($this->giftTable.' as b' ,'a.gift_id','=','b.gift_id')
                ->where('a.pool_id', $info['id'])
                ->select(['a.gift_id','b.name as gift_name','b.image as gift_image','b.price as gift_price']);

            $list = $query->orderBy('a.item_no', 'asc')->get();
            $list = objToArray($list);

        } while (false);

        return $list;
    }

    //擂主玩法新增奖池白名单
    public function wishDefenderAddPoolWhite($data, $user){
        $data['admin_id'] = $user['id'];
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderAddPoolWhite', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法删除奖池白名单
    public function wishDefenderDelPoolWhite($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderDelPoolWhite', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法取消投放奖池白名单
    public function wishDefenderCancelPoolWhite($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderCancelPoolWhite', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法奖池白名单列表
    public function wishDefenderPoolWhiteList(Request $request, $adminUser)
    {
        $user_id = $request->input('user_id');
        $gift_id = $request->input('gift_id');
        $uuid = $request->input('uuid');
        $status = $request->input('status');
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $pool_level = $request->get('pool_level',1000);

        $query = DB::connection($this->connection)
            ->table($this->wWhiteTable.' as a')
            ->leftJoin($this->giftTable.' as b' ,'a.gift_id','=','b.gift_id')
            ->leftJoin($this->userTable.' as c' ,'a.user_id','=','c.user_id')
            ->select(['a.id','a.user_id','a.gift_id','a.status','a.order_id','a.admin_id','a.created_at','a.pool_id'
                ,'b.name as gift_name','b.image as gift_image','b.price as gift_price'
                ,'c.uuid','c.nickname'])
            ->where('a.pool_id', '>', 0)
            ->where('a.is_delete', 0);
        $query = $query->where('a.pool_level', $pool_level);

        if($adminUser->id != 18) {
            $query = $query->where('a.admin_id', '<>', 18);
        }

        if(!empty($user_id)) {
            $query = $query->where('a.user_id', $user_id);
        }
        if(!empty($gift_id)) {
            $query = $query->where('b.gift_id', $gift_id);
        }
        if(!empty($uuid)) {
            $query = $query->where('c.uuid', $uuid);
        }
        if($status >= 0) {
            $query = $query->where('a.status', $status);
        }
        if(!empty($date_st)) {
            $query = $query->where('a.created_at', '>=', date("Y-m-d H:i:s", strtotime($date_st)));
        }
        if(!empty($date_ed)) {
            $query = $query->where('a.created_at', '<=', date("Y-m-d H:i:s", strtotime($date_ed)));
        }

        $list = $query->orderBy('a.status', 'asc')->orderBy('a.id', 'desc')->get();
        $list = objToArray($list);
        if(!empty($list)) {
            $adminIds = array_column($list, 'admin_id');
            $adminList = DB::table('users')->whereIn('id', $adminIds)->select(['id','name'])->get();
            $adminList = array_column(objToArray($adminList), null, 'id');

            foreach($list as $key=>$val) {
                $val['admin_name'] = empty($adminList[$val['admin_id']]['name']) ? '' : $adminList[$val['admin_id']]['name'];
                $val['cur_admin_id'] = $adminUser->id;
                $list[$key] = $val;
            }
        }

        return ['code'=>20000, 'data'=>$list, 'msg'=>'ok'];
    }

    //擂主玩法个人池奖池列表
    public function wishDefenderUserPoolList(Request $request)
    {
        $status = $request->input('status');
        $pool_type = $request->input('pool_type', 0);

        $query = DB::connection($this->connection)->table($this->wPoolTable);
        if(!empty($status)) {
            $query = $query->where('status', $status);
        }
        if($pool_type > 1) {
            $query = $query->where('pool_type', $pool_type);
        }else{
            $query = $query->whereIn('pool_type', [2,3]);
        }

        $list = $query->get();
        $list = objToArray($list);

        return ['code'=>20000, 'data'=>$list, 'msg'=>'ok'];
    }

    //擂主玩法更新进入个人池配置
    public function wishDefenderSetInUserPoolConfig($data, $user){
        $data['admin_id'] = $user['id'];
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderSetInUserPoolConfig', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法更新离开个人池配置
    public function wishDefenderSetOutUserPoolConfig($data, $user){
        $data['admin_id'] = $user['id'];
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderSetOutUserPoolConfig', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

    //擂主玩法个人池汇总数据
    public function wishDefenderUserPoolStat(Request $request)
    {
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $user_id = $request->input('user_id');
        $pool_type = $request->input('pool_type', 0);
        $in_user_pool = $request->input('in_user_pool', 0);//是否在个人池 1=是 2=否 -1=全部

        //个人池
        $query1 = DB::connection($this->connection)->table($this->wPoolTable);
        if($pool_type == 2) {
            $query1 = $query1->where('pool_type', 2);
        }elseif($pool_type == 3) {
            $query1 = $query1->where('pool_type', 3);
        }else{
            $query1 = $query1->whereIn('pool_type', [2,3]);
        }
        $poolList = $query1->get();
        $poolList = objToArray($poolList);
        $poolIds = array_column($poolList, 'id');
        $poolList = array_column($poolList, null, 'id');

        //个人池用户
        $poolUserIds = DB::connection($this->connection)->table($this->wPoolUserTable)->where('is_delete', 0)->select(['id', 'user_id'])->get();
        $poolUserIds = objToArray($poolUserIds);
        $poolUserIds = array_column($poolUserIds, null, 'user_id');
        $userIds = array_column($poolUserIds, 'user_id');

        $query2 = DB::connection($this->connection)->table($this->wDrawTable)
            ->where('white_id', 0)
            ->whereIn('pool_id', $poolIds);
        if(!empty($date_st)) {
            $query2 = $query2->where('created_at', '>=', date("Y-m-d H:i:s", strtotime($date_st)));
        }
        if(!empty($date_ed)) {
            $query2 = $query2->where('created_at', '<=', date("Y-m-d H:i:s", strtotime($date_ed)));
        }
        //是否在个人池
        if($in_user_pool == 1) {
            if(!empty($user_id)) {
                if(in_array($user_id, $userIds)) {
                    $query2 = $query2->whereIn('user_id', [$user_id]);
                }else{
                    $query2 = $query2->whereIn('user_id', []);
                }
            }else{
                $query2 = $query2->whereIn('user_id', $userIds);
            }
        }elseif($in_user_pool == 2) {
            if(!empty($user_id)) {
                if(in_array($user_id, $userIds)) {
                    $query2 = $query2->whereNotIn('user_id', []);
                }else{
                    $query2 = $query2->whereIn('user_id', [$user_id]);
                }
            }else{
                $query2 = $query2->whereNotIn('user_id', $userIds);
            }
        }else{
            if(!empty($user_id)) {
                $query2 = $query2->where('user_id', $user_id);
            }
        }

        //列表
        $data = $query2->selectRaw('user_id, sum(prop_diamond_num) as prop_diamond_num, sum(reward_diamond_num) as reward_diamond_num, max(created_at) AS last_at, count(1) as draw_num')
            ->groupBy('user_id')
            ->orderBy('last_at', 'desc')
            ->paginate($limit, ['*'], 'page', $page);
        $data = objToArray($data);

        //合计数据
        $query4 = DB::connection($this->connection)->table($this->wDrawTable)
            ->where('white_id', 0)
            ->whereIn('pool_id', $poolIds);
        if(!empty($date_st)) {
            $query4 = $query4->where('created_at', '>=', date("Y-m-d H:i:s", strtotime($date_st)));
        }
        if(!empty($date_ed)) {
            $query4 = $query4->where('created_at', '<=', date("Y-m-d H:i:s", strtotime($date_ed)));
        }
        //是否在个人池
        if($in_user_pool == 1) {
            if(!empty($user_id)) {
                if(in_array($user_id, $userIds)) {
                    $query4 = $query4->whereIn('user_id', [$user_id]);
                }else{
                    $query4 = $query4->whereIn('user_id', []);
                }
            }else{
                $query4 = $query4->whereIn('user_id', $userIds);
            }
        }elseif($in_user_pool == 2) {
            if(!empty($user_id)) {
                if(in_array($user_id, $userIds)) {
                    $query4 = $query4->whereNotIn('user_id', []);
                }else{
                    $query4 = $query4->whereIn('user_id', [$user_id]);
                }
            }else{
                $query4 = $query4->whereNotIn('user_id', $userIds);
            }
        }else{
            if(!empty($user_id)) {
                $query4 = $query4->where('user_id', $user_id);
            }
        }
        $data2 = $query4->selectRaw('count(DISTINCT user_id) as user_num, sum(prop_diamond_num) as prop_diamond_num, sum(reward_diamond_num) as reward_diamond_num, count(1) as draw_num')
            ->first();
        $data2 = objToArray($data2);
        $data2['user_num'] = empty($data2['user_num']) ? 0 : $data2['user_num'];
        $data2['draw_num'] = empty($data2['draw_num']) ? 0 : $data2['draw_num'];
        $data2['prop_diamond_num'] = empty($data2['prop_diamond_num']) ? 0 : $data2['prop_diamond_num'];
        $data2['reward_diamond_num'] = empty($data2['reward_diamond_num']) ? 0 : $data2['reward_diamond_num'];
        //返奖率：产出钻石数/消耗钻石数
        $data2['output_ratio'] = ($data2['reward_diamond_num']>0) ? round(($data2['reward_diamond_num']/$data2['prop_diamond_num'])*100,4) : '0.0000';
        //盈亏：产出钻石数-消耗钻石数
        $data2['profit_loss'] = $data2['reward_diamond_num'] - $data2['prop_diamond_num'];

        $result = ['list'=>[], 'all'=>$data2, 'total'=>0];
        if(!empty($data['data'])) {
            $result['total'] = $data['total'];

            $userList = DB::connection($this->connection)->table($this->userTable)->whereIn('user_id', array_column($data['data'], 'user_id'))->select('user_id','nickname','uuid')->get();
            $userList = array_column(objToArray($userList), null, 'user_id');

            $list = [];
            foreach($data['data'] as $key=>$val) {
                $val['nickname'] = empty($userList[$val['user_id']]['nickname']) ? '' : $userList[$val['user_id']]['nickname'];
                $val['uuid'] = empty($userList[$val['user_id']]['uuid']) ? '' : $userList[$val['user_id']]['uuid'];
                $val['output_ratio'] = ($val['reward_diamond_num']>0) ? round(($val['reward_diamond_num']/$val['prop_diamond_num'])*100,4) : '0.0000';
                $val['profit_loss'] = $val['reward_diamond_num'] - $val['prop_diamond_num'];

                $val['in_user_pool'] = 2;
                $val['in_user_pool_id'] = 0;
                if(!empty($poolUserIds[$val['user_id']])) {
                    $val['in_user_pool'] = 1;
                    $val['in_user_pool_id'] = $poolUserIds[$val['user_id']]['id'];
                }

                $list[$key] = $val;
            }

            $result['list'] = $list;
        }

        return ['code'=>20000, 'data'=>$result, 'msg'=>'ok'];
    }

    //擂主玩法奖池更新阀值
    public function wishDefenderSetUserPoolConfig($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/wishDefenderSetUserPoolConfig', $data, 'json', 'POST');
        return curlResultHandle($res);
    }

}
